package com.qf.mvc2203.controller;

import com.sun.deploy.net.HttpResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/download")
public class DownloadController {

    @Value("${uploadpath}")   // 依赖注入 文件存放路径
    private String filepath;

    /**
     * 文件下载接口，返回值为 void
     *
     */
    @RequestMapping("/test1")
    public void test1(String name , HttpServletResponse response) throws IOException {

        //1. 根据传入的文件名找到要下载的文件
        final String finalFilePath = filepath + name;

        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+name);

        //2. 把文件内容写入响应体中
        IOUtils.copy(new FileInputStream(finalFilePath),response.getOutputStream());

    }


    /**
     * 从 webapp发布目录下的img目录中下载文件
     * 采用 servletContext 的方法，把 发布目录下的img的相对路径转成绝对路径
     */
    @RequestMapping("/test2")
    public void test2(String name , HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取文件存放的路径
        final ServletContext servletContext = request.getServletContext();

        // 获取 web根目录下img的绝对路径
        final String realPath = servletContext.getRealPath("/img");

        // 拼装最终的文件路径，注意分隔符号 File.separator
        final String finalFileName = realPath + File.separator + name;

        response.setHeader("content-disposition","attachment;filename="+name);

        IOUtils.copy(new FileInputStream(finalFileName),response.getOutputStream());


    }

}
